package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.admin.config.ALiYunConfig;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WemediaFeign;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.mapper.AdSensitiveMapper;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    private WemediaFeign wemediaFeign;
    @Value("${fdfs.url}")
    private String fdfsImageUrl;

    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        if (id == null) {
            log.error("id不存在");
            return;
        }
        WmNews wmNews = wemediaFeign.findById(id);
        if (wmNews == null) {
            log.error("审核的自媒体文章不存在,自媒体的id：{}", id);
            return;
        }
        //如果状态为4（人工审核通过），直接保存数据和创建索引
        if (wmNews.getStatus() == 4) {
            saveAppArticle(wmNews);
            return;
        }
        //如果状态为8（审核通过），并且发布时间小于当前时间，保存数据创建索引
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            saveAppArticle(wmNews);
            return;
        }
        //如果当前状态为1
        if (wmNews.getStatus() == 1) {
            //首先提取文章中的图片和文字
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            //文本审核
            boolean textScanBoolean = handleTextScan((String) contentAndImagesResult.get("content"), wmNews);
            if (!textScanBoolean) return;
            //图片审核
            boolean ImagesScanBoolean = handleImagesScan((List<String>) contentAndImagesResult.get("images"), wmNews);
            if (!ImagesScanBoolean) return;
            //敏感词审核
            boolean senstiveScanBoolean = handleSenetiveScan((String) contentAndImagesResult.get("content"), wmNews);
            if (!senstiveScanBoolean) return;
            //发布的时间大于当前的时间，修改状态为8
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()){
                updateWmNews(wmNews , (short) 8 , "审核通过，待发布");
                return;
            }
            saveAppArticle(wmNews);
        }


    }

    @Autowired
    private AdSensitiveMapper adSensitiveMapper;
    /**
     * 敏感词审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleSenetiveScan(String content, WmNews wmNews) {
        boolean flag = true;
        List<String> allSensitive = adSensitiveMapper.findAllSensitive();
        SensitiveWordUtil.initMap(allSensitive);
        Map<String, Integer> map = SensitiveWordUtil.matchWords(content);
        if (map.size() > 0){
            log.error("敏感词过滤没有通过，包含了敏感词:{}", map);
            updateWmNews(wmNews , (short)2 , "文章中有敏感词，审核不通过");
            flag = false;
        }
        return flag;
    }

    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FastDFSClient fastDFSClient;
    /**
     * 图片审核
     * @param images
     * @param wmNews
     * @return
     */
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        if (images == null){
            return true;
        }
        boolean flag = true;
        List<byte []> list = new ArrayList<>();
        try {
            for (String image : images) {
                String imageName = image.replace(fdfsImageUrl, "");
                int index = imageName.indexOf("/");
                String groupName = imageName.substring(0, index);
                String imagePath = imageName.substring(index + 1);
                byte[] imageList = fastDFSClient.download(groupName, imagePath);
                list.add(imageList);
                Map map = greenImageScan.imageScan(list);
                if (!map.get("suggestion").equals("pass")){
                    if (map.get("suggestion").equals("block")){
                        updateWmNews(wmNews, (short) 2, "文章中图片有违规");
                        flag = false;
                    }
                    if (map.get("suggestion").equals("review")){
                        updateWmNews(wmNews, (short) 3, "文章中有不确定图片");
                        flag = false;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    @Autowired
    private GreeTextScan greeTextScan;
    /**
     * 纯文本审核
     * @param content
     * @param wmNews
     * @return
     */
    private boolean handleTextScan(String content, WmNews wmNews) {
        boolean flag = true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            if (!map.get("suggestion").equals("pass")){
                if (map.get("suggestion").equals("block")){
                    updateWmNews(wmNews, (short) 2, "文章内容中有敏感词汇");
                    flag = false;
                }
                if (map.get("suggestion").equals("review")){
                    updateWmNews(wmNews, (short) 3, "文章内容中有不确定词汇");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    private void updateWmNews(WmNews wmNews, short i, String msg) {
        wmNews.setStatus(i);
        wmNews.setReason(msg);
        wemediaFeign.updateWmNews(wmNews);
    }


    //提取文章中的文字和图片
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        String content = wmNews.getContent();
        //存储文本内容
        StringBuilder sb = new StringBuilder();
        //存储图片内容
        List<String> images = new ArrayList<>();
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        for (Map map : contentList) {
            if (map.get("type").equals("text")){
                sb.append(map.get("value"));
            }
            if (map.get("type").equals("image")){
                images.add((String) map.get("value"));
            }
        }
        if (wmNews.getImages() != null && wmNews.getType() != 0){
            String[] split = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(split));
        }
        Map<String , Object> resultMap = new HashMap<>();
        resultMap.put("content" , sb.toString());
        resultMap.put("images" , images);
        return resultMap;
    }

    @Autowired
    private ArticleFeign articleFeign;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    //保存自媒体文章
    private void saveAppArticle(WmNews wmNews) {
        //保存文章信息，需要返回当前文章，获取到文章的主键
        ApArticle apArticle = saveArticle(wmNews);

        //保存文章配置信息
        saveArticleConfig(apArticle);

        //保存文章内容
        saveArticleContent(apArticle ,wmNews);

        wmNews.setArticleId(apArticle.getId());
        updateWmNews(wmNews , (short)9 , "审核通过");

        //TODO es索引创建
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", apArticle.getId());
        map.put("publishTime", apArticle.getPublishTime());
        map.put("layout", apArticle.getLayout());
        map.put("images", apArticle.getImages());
        map.put("authorId", apArticle.getAuthorId());
        map.put("title", apArticle.getTitle());
        IndexRequest indexRequest = new IndexRequest("app_info_article").id(apArticle.getId().toString()).source(map);
        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);
    }

    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsForward(true);
        articleFeign.saveArticleConfig(apArticleConfig);
    }

    @Autowired
    private AdChannelMapper adChannelMapper;
    /**
     * 保存文章信息
     * @param wmNews
     * @return
     */
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setFlag((byte) 0);
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());
        apArticle.setPublishTime(wmNews.getPublishTime());
        apArticle.setLayout(wmNews.getType());

        Integer userId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById(userId);
        if (wmUser != null){
            String name = wmUser.getName();
            ApAuthor apAuthor = articleFeign.selectAuthorByName(name);
            if (apAuthor != null){
                apArticle.setAuthorId(apAuthor.getId().longValue());
                apArticle.setAuthorName(apAuthor.getName());
            }
        }

        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelMapper.selectById(channelId);
        if (adChannel != null){
            apArticle.setChannelId(adChannel.getId());
            apArticle.setChannelName(adChannel.getName());
        }
        return articleFeign.saveArticle(apArticle);
    }

    //分页查询文章列表
    @Override
    public ResponseResult findNews(NewsAuthDto dto) {
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        PageResponseResult list = wemediaFeign.findList(dto);
        list.setHost(fdfsImageUrl);
        return list;
    }

    //根据id查询文章详情
    @Override
    public ResponseResult findOne(Integer id) {
        if (id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        ResponseResult result = ResponseResult.okResult(wmNewsVo);
        result.setHost(fdfsImageUrl);
        return result;
    }

    //修改文章状态
    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        if (dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = wemediaFeign.findById(dto.getId());
        if (wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //人工审核不通过
        if (type.equals(0)){
            updateWmNews(wmNews , (short) 2 , dto.getMsg());
        }else if (type.equals(1)){
            updateWmNews(wmNews , (short)4 , "审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
